<template>
  <div class="pd30 bind-select">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>电梯绑定查询</div>
      </div>
      <div class="bind-main">
        <div class="pl bind-top flex">
          <div class="flex flexac">
            <div class="flex flexac ">
              <!-- <span class="reg-name">注册代码：</span> -->
              <el-input v-model="parma.registerCode" class="reg-input" type="number" placeholder="请输入注册代码" @input="getBindElevator" />
            </div>
            <div class="rescueCode flex flexac m-l-20">
              <!-- <span class="res-name">位置码：</span> -->
              <el-input v-model="parma.rescueCode" class="res-input co-input" placeholder="请输入位置码" @input="getBindElevator" />
            </div>
            <div class="groupbtn flex m-l-40 ">
              <el-button class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getBindElevator"><i class="co-i" /><span class="search1">查 询</span></el-button>
              <el-button class=" co-empty flexcenter m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
            </div>
            <!-- <div class="flex flexac">
              <span class="nameText">地址：</span>
              <el-input v-model="parma.name" class="input" placeholder="请输入地址" />
            </div> -->
          </div>
          <!-- <div class="flex flexac m-t-15">

            <div class="flex flexac">
              <span class="nameText">绑定状态：</span>
              <el-select v-model="bindSelect.usageStateVal" placeholder="请选择绑定状态">
                <el-option v-for="item in bindSelect.usageState" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div class="groupbtn flex m-l-40 ">
              <el-button class="flex flexac m-r-20 fs14" size="small" type="warning" @click="getBindElevator"><i class="co-i" /><span class="search1">查 询</span></el-button>
              <el-button class=" co-empty flexcenter m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
            </div>
          </div> -->
        </div>
        <div class="con-row flex flexac flexjcsb pl">
          <div>
            <!-- <el-button class="defaultbtn" type="danger" @click="handleAddMaintenance">新增电梯信息</el-button> -->
            <el-button class="defaultbtn" type="primary" @click="handleRefresh"><i class="el-icon-refresh" :class="refresh?'goRefresh':''" />刷 新</el-button>

          </div>
          <div class="m-r-25 flex">
            <el-button type="danger" class="defaultbtn" @click="handleAddMaintenance"><i class="iconfont icon-xinzeng mr3" />新增</el-button>
            <el-button class="defaultbtn" type="success" @click="handleImport"><i class="iconfont icon-daoru mr3" />导入</el-button>

            <el-button class="defaultbtn" type="primary" @click="handleExportExcel"><i class="iconfont icon-wenjiandaochu" />导出</el-button>
            <div class="pre m-l-10">
              <el-button class="defaultbtn pre" type="primary" @click="handleSenior('field')"><i class="iconfont icon-lie" />字段
              </el-button>
              <div class="selectUl br1" :class="seniorSet.field?'showSelectUl':'hideSelectUl'">
                <div v-for="(item,i) in tablehead" :key="i" class="li">
                  <el-checkbox v-model="item.isShow">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
            <div class="pre m-l-10">
              <el-button class="defaultbtn" type="primary" @click="handleSenior('sortable')"><i class="iconfont icon-paixu" />排序</el-button>
              <div class="selectUl br1" :class="seniorSet.sortable?'showSelectUl':'hideSelectUl'">
                <div v-for="(item,i) in tablehead" v-if="item.isShow" :key="i" class="li">
                  <el-checkbox v-model="item.sortable">{{ item.label }}</el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-table
          id="factorytable"
          ref="factorytable"
          class="con-table"
          type="expand"
          :data="factorytable"
          style="width: 100%"
          highlight-current-row
        >
          <template v-for="(item,i) in tablehead">
            <el-table-column v-if="item.isShow" :key="i" align="center" :width="item.width" :sortable="item.sortable" :show-overflow-tooltip="true" :prop="item.prop" :label="item.label" />
          </template>
          <el-table-column label="绑定状态" align="center" width="90">
            <template slot-scope="scope">
              <span :class="`status-${scope.row.bindState}`">
                {{
                  scope.row.bindState === 0 ? '未绑定' :
                  scope.row.bindState === 1 ? '已录入' :
                  scope.row.bindState === 2 ? '已申请' :
                  scope.row.bindState === 3 ? '已绑定' :
                  scope.row.bindState === 4 ? '已拒绝' : '未确认'
                }}
              </span>
            </template>
          </el-table-column>
          <!-- prop="name" -->
          <el-table-column label="基本操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button class="btn" :disabled="scope.row.bindState === 3" type="primary" @click="handleModify(scope.$index, scope.row)">
                <i class="el-icon-edit" />编辑</el-button>
              <!-- 绑定 -->
              <el-button
                v-if="scope.row.bindState === 0"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                type="primary"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
                @click="handleEdit(scope.$index, scope.row)"
              >
                绑 定
              </el-button>
              <!-- 申请中 -->
              <el-button
                v-if="scope.row.bindState === 1"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
              >
                申请中
              </el-button>
              <!-- 绑定中 -->
              <el-button
                v-if="scope.row.bindState === 2"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
              >
                绑定中
              </el-button>
              <!-- 解绑 -->
              <el-button
                v-if="scope.row.bindState === 3"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
                @click="handleUnbundling(scope.$index, scope.row)"
              >
                解 绑
              </el-button>
              <!-- 绑定 -->
              <el-button
                v-if="scope.row.bindState === 4"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                size="mini"
                type="primary"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
                @click="handleEdit(scope.$index, scope.row)"
              >
                绑 定
              </el-button>
              <!-- 未确认 -->
              <el-button
                v-if="scope.row.bindState === 5"
                :class="`btn-${scope.row.bindState} el-icon-edit  btn`"
                type="primary"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
                @click="handleEdit(scope.$index, scope.row)"
              >
                绑 定
              </el-button>
              <!-- <el-button
                :class="`btn-${scope.row.bindState} el-icon-edit defaultbtn btn`"
                type="primary"
                size="mini"
                :disabled="scope.row.bindState === 1 || scope.row.bindState === 2"
                @click="handleEdit(scope.$index, scope.row)"
              >
                {{
                  scope.row.bindState === 0 ? '绑 定' :
                  scope.row.bindState === 1 ? '申请中' :
                  scope.row.bindState === 2 ? '绑定中' :
                  scope.row.bindState === 3 ? '解 绑' :
                  scope.row.bindState === 4 ? '绑 定' : '未确认'
                }}
              </el-button> -->
              <el-button type="danger" :disabled="scope.row.bindState === 3" class="btn" @click="handleDeleteBtn(scope.$index, scope.row)"><i class="el-icon-delete-solid" />删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="paginationWrap flex "
          :current-page="paging.currentPage"
          :page-sizes="paging.pageSizeArr"
          :page-size="paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 信息绑定 -->
    <BindeElevator v-model="bindVisible" :data="editFactory" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseBindDialog" />
    <!-- 电梯信息录入 -->
    <InfoMationEntry v-model="infoData.infoVisible" :is-edit="isEdit" :data="infoData.data" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseDialog" />

    <!-- 修改 -->
    <Modify v-model="moVisible" :data="moData" @handleRefresh="handleRefresh" @handleCloseDialog="handleCloseMoDialog" />
  </div>
</template>

<script>

import BindeElevator from './dialog/index'
import Modify from './dialog/modify'
import InfoMationEntry from './dialog/InformationEntry'
import { showNotice, formatDateTime } from '@/utils/toolclass'
import { elevatorQueryList, elevatorDelete, elevatorDetail } from '@/api/elevator/elevator'
import { unbindElevator } from '@/api/elevator/elevatorRelationship'

import storage from '@/utils/storage'

export default {
  name: 'BindSelect',
  components: {
    BindeElevator,
    InfoMationEntry,
    Modify
  },
  props: {},
  data() {
    return {
      bindVisible: false,
      infoData: {
        infoVisible: false,
        data: null
      },
      moVisible: false,
      moData: null,
      bindSelect: {
        usageStateVal: '',
        usageState: [
          {
            value: '1',
            label: '在用'
          }, {
            value: '2',
            label: '停用'
          }, {
            value: '3',
            label: '不属'
          }, {
            value: '4',
            label: '不明'
          }, {
            value: '5',
            label: '公告注销'
          }, {
            value: '6',
            label: '提交监察'
          }, {
            value: '7',
            label: '正在大修'
          }, {
            value: '8',
            label: '正在安装'
          }, {
            value: '9',
            label: '正在改造'
          }]
      },
      paging: {
        currentPage: 1,
        pageSize: 10,
        pageSizeArr: [10, 20, 50, 100],
        total: 0
      },
      factorytable: [],
      param: {
        id: '',
        name: ''
      },
      parma: {
        bindState: '',
        id: '',
        registerCode: '',
        registerUnit: '',
        rescueCode: '',
        maintenanceUnitId: '',
        useUnitId: ''
      },
      maintenanceUnit: [],
      editFactory: {},
      isEdit: false,
      selectDataLength: 0,
      refresh: false,
      seniorSet: {
        'field': false,
        'sortable': false
      },
      tablehead: [
        {
          index: 0,
          prop: 'index',
          label: '序号',
          width: '70',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'rescueCode',
          label: '救援代码',
          width: '80',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'registerCode',
          label: '注册代码',
          width: '180',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 3,
          prop: 'villageName',
          label: '小区名称',
          width: '100',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 4,
          prop: 'usePlaceName',
          label: '场所名称',
          width: '140',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 5,
          prop: 'useUnitName',
          label: '使用单位',
          width: '100',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 6,
          prop: 'installAddress',
          label: '安装地址',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 7,
          prop: 'maintenancePerson1',
          label: '第一维保人',
          width: '90',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 8,
          prop: 'maintenancePerson1Phone',
          label: '第一维保人手机号码',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ]
    }
  },
  computed: {},
  watch: {},
  created() {
    this.userInfo = JSON.parse(storage.get('userInfo'))
    this.getBindElevator()
  },
  mounted() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/bindSelect' }))
  },
  methods: {
    handleImport() {
      this.$router.push({ path: '/dossierImport' })
    },
    handleAddMaintenance() {
      this.infoData.infoVisible = true
      this.isEdit = false
      this.infoData.data = {
        bindState: 0, // 绑定状态（0：未绑定；1：已录入；2：已申请；3：已绑定；4：已拒绝；5：未确认；）
        carNo: '', // 厂车牌照编号
        factoryCode: '', // 出厂代码
        factoryNo: '', // 出厂编号
        id: '', // ID
        installAddress: '', // 安装地址（查询）
        internaNo: '', // 单位内部编号
        maintenancePerson1: '', // 第一维保人姓名（查询）
        maintenancePerson1Id: '', // 第一维保人ID
        maintenancePerson1Name: '', // 第一维保人姓名
        maintenancePerson1Phone: '', // 第一维保人手机号（查询）
        maintenancePerson2Id: '', // 第二维保人ID
        maintenancePerson2Name: '', // 第二维保人姓名
        maintenancePerson2Phone: '', // 第二维保人手机号
        maintenanceUnitId: '', // 维保单位ID
        maintenanceUnitName: '', // 维保单位名称
        manufacturerUnitId: '', // 生产厂家ID
        manufacturerUnitName: '', // 生产厂家名称
        nextInspectionDate: '', // 下次检验日期
        operator: '', // 操作人员
        registerCode: '', // 电梯注册代码
        registerDate: '', // 注册登记日期
        registerUnit: '', // 注册登记机构
        registerUpdateDate: '', // 注册更新日期
        remark: '', // 备注
        rescueCode: '', // 救援代码（位置码）
        securityPerson: '', // 安全管理员姓名
        securityPersonPhone: '', // 安全管理员手机
        supportUnit: '', // 保养技术支持单位
        usePlaceId: '', // 电梯使用场所ID
        usePlaceName: '', // 使用场合名称（查询）
        useUnitId: '', // 使用单位ID
        useUnitName: '', // 使用单位（查询）
        version: '', // 版本号
        villageId: '', // 小区ID
        villageName: '' // 小区名称（查询）
      }
    },
    handleSenior(type) {
      if (type === 'field') {
        this.seniorSet.field = !this.seniorSet.field
        this.seniorSet.sortable = false
      }
      if (type === 'sortable') {
        this.seniorSet.field = false
        this.seniorSet.sortable = !this.seniorSet.sortable
      }
    },
    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['ID', '救援代码', '注册代码', '场所名称', '使用单位', '安装地址', '第一维保人', '第一维保人手机号码', '绑定状态']
        const filterVal = ['id', 'rescueCode', 'registerCode', 'usePlaceName', 'useUnitName', 'installAddress', 'maintenancePerson1', 'maintenancePerson1Phone', 'bindState']
        const data = this.formatJson(filterVal, this.factorytable)
        export_json_to_excel(tHeader, data, '电梯绑定列表(' + formatDateTime().ymd) + ')'
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleRefresh() {
      this.refresh = true
      this.getBindElevator()
      setTimeout(() => {
        this.refresh = false
      }, 1200)
    },
    getBindElevator() {
      elevatorQueryList(this.parma.bindState, this.parma.id, this.parma.maintenanceUnitId, this.paging.currentPage, this.paging.pageSize, this.parma.registerCode, this.parma.registerUnit, this.parma.rescueCode, this.parma.useUnitId).then((res) => {
        if (res.code === '000000') {
          // console.log(res)
          this.factorytable = res.data.map((item, i) => {
            const items = {
              index: i + 1,
              bindState: item.bindState,
              carNo: item.carNo,
              factoryNo: item.factoryNo,
              id: item.id,
              installAddress: item.installAddress,
              internaNo: item.internaNo,
              maintenancePerson1: item.maintenancePerson1,
              maintenancePerson1Phone: item.maintenancePerson1Phone,
              maintenanceUnitId: item.maintenanceUnitId,
              maintenanceUnitName: item.maintenanceUnitName,
              manufacturerUnitId: item.manufacturerUnitId,
              manufacturerUnitName: item.manufacturerUnitName,
              nextInspectionDate: item.nextInspectionDate,
              operator: item.operator,
              registerCode: item.registerCode,
              registerDate: item.registerDate,
              registerUnit: item.registerUnit,
              registerUpdateDate: item.registerUpdateDate,
              remark: item.remark,
              rescueCode: item.rescueCode,
              usePlaceName: item.usePlaceName,
              useUnitId: item.useUnitId,
              useUnitName: item.useUnitName,
              version: item.version,
              villageId: item.villageId,
              villageName: item.villageName
            }
            return items
          })
          this.paging = {
            pageSize: res.pager.pageSize,
            currentPage: res.pager.pageIndex,
            total: res.pager.totalSize
          }
        }
      })
    },
    handleEmptySearch() {
      this.parma.registerCode = ''
      this.parma.rescueCode = ''
      this.parma.maintenanceUnitId = ''
      this.parma.useUnitId = ''
      this.getBindElevator()
    },
    handleModify(index, row) {
      this.moVisible = true
      elevatorDetail(row.id).then(res => {
        // console.log(res.data)
        if (res.code === '000000') {
          this.moData = res.data
        }
      })
    },
    // 绑定
    handleEdit(index, row) {
      this.bindVisible = true
      this.isEdit = true
      this.editFactory = row
    },
    // 解绑
    handleUnbundling(index, row) {
      // console.log(row)
      this.$confirm('确定要解除绑定吗？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存',
        cancelButtonText: '取消'
      })
        .then(() => {
          unbindElevator({ id: row.id }).then(res => {
            if (res.code === '000000') {
              showNotice('success', '提示', '解绑成功')
              this.handleRefresh()
            } else {
              if (res.msg === '失败') {
                showNotice('error', '提示', '解绑失败')
              } else {
                showNotice('error', '提示', res.msg)
              }
            }
          })
        })
        .catch(action => {
          showNotice('success', '提示', '取消成功')
        })
    },
    // 单选操作，全选按钮失效操作
    handleCheck(selection, row) {
      this.$refs.factorytable.clearSelection()
      if (selection.length === 0) { // 判断selection是否有值存在
        return
      }
      if (row) {
        this.selectioned = row
        this.row = row
        this.$refs.factorytable.toggleRowSelection(row, true)
      }
    },

    // 取消单选的checkbox
    handleCheckChange(row) {
      if (row.length === 0) {
        this.selectioned = null
      }
    },
    handleDeleteBtn(index, row) {
      this.$alert('这个操作会删除和它相关联的所有数据,确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.handleDelete(row.id)
          }
        }
      })
    },
    handleDelete(id) {
      elevatorDelete(id).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '删除成功')
          this.getBindElevator()
        }
      })
    },
    handleCloseDialog() {
      this.infoData.infoVisible = !this.infoData.infoVisible
    },
    handleCloseMoDialog() {
      this.moVisible = !this.moVisible
    },
    handleCloseBindDialog() {
      this.bindVisible = !this.bindVisible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      this.getBindElevator()
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
      this.getBindElevator()
    }
  }
}
</script>
<style scoped lang="scss">
.bind-select {
  .bind-main {
    .btn {
      width: 78px;
      height: 34px;
      line-height: 6px;
      font-size: 12px;
      vertical-align: middle;
    }
    .status-0 {
      color: red;
      font-size: 16px;
      font-weight: 700;
    }
    .status-1 {
      color: darkgoldenrod;
      font-size: 16px;
      font-weight: 700;
    }
    .status-2 {
      color: blue;
      font-size: 16px;
      font-weight: 700;
    }
    .status-3 {
      font-size: 16px;
      font-weight: 700;
    }
    .status-4 {
      font-size: 16px;
      font-weight: 700;
    }
    .status-5 {
      font-size: 16px;
      font-weight: 700;
    }
    .btn-0 {}
    .btn-1 {
      background: silver;
      color: #ffffff;
    }
    .btn-2 {
      background: silver;
      color: #ffffff;
    }
    .btn-3 {
      background: #67C23A;
      color: #ffffff;
    }
    .btn-4 {}
    .btn-5 {
      color: #ffffff;
    }
    .bind-top {
      height: 80px;
      background: #eeeeee;
      .reg-name {}
      .res-name {}
      .unit-name {}
      .reg-input {
        width: 200px;
      }
      .co-input {
        width: 180px !important;
      }
    }
  }
}
</style>
